package com.hnyc.common;

import com.alibaba.fastjson2.JSON;
import com.hnyc.config.FacadeConfig;
import com.hnyc.facade.domain.AuthCallbackParam;
import com.hnyc.facade.shopee.GoodsListParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

/**
 * @auther zero
 * @date 2023/3/12
 **/
@Slf4j
@Component
public class FacadeClient {
    OkHttpClient client;
    static MediaType mediaType = MediaType.parse("application/json");
    InnerFacadeUrl innerFacadeUrl;
    @Resource
    FacadeConfig facadeConfig;
    @PostConstruct
    public void initClient(){
        client=new OkHttpClient.Builder()
                .callTimeout(30, TimeUnit.SECONDS)
                .readTimeout(10,TimeUnit.SECONDS)
                .addInterceptor(chain -> {
                    Request request = chain.request();


                    Headers headers = request.headers().newBuilder()
                            .add("Content-Type", "application/json")
                            .add("Authorization", "Bearer " + encodeAuth())
                            .build();


                    long t1 = System.nanoTime();
                    log.info(String.format("发送请求: [%s] %s%n%s",
                            request.url(), chain.connection(), request.headers()));

                    Response response = chain.proceed(request.newBuilder()
                    .headers(headers)
                    .build());

                    long t2 = System.nanoTime();

                    log.info(String.format("接收响应: [%s] %.1fms%n%s",
                            response.request().url(),
                            (t2 - t1) / 1e6d,
                            response.headers()));

                    return response;
                })
        .build();
        innerFacadeUrl =new InnerFacadeUrl(facadeConfig);
    }

    public void registerShop(AuthCallbackParam param,Callback callback){

        Request req = new Request.Builder()
                .url(innerFacadeUrl.registerShop())
//                .addHeader("Content-Type", "application/json")
//                .addHeader("Authorization", "Bearer " + encodeAuth())
                .post(createBody(param))
                .build();
        client.newCall(req).enqueue(callback);

    }
    public void goodsList(GoodsListParam req, Callback callback){
        client.newCall(
                req.reqBuilder().post(createBody(req)).build()
        ).equals(callback);
    }
    private RequestBody createBody(Object param){
        return RequestBody.create(mediaType, JSON.toJSONString(param));
    }
    private String encodeAuth(){
        try {
            return Base64.getEncoder().encodeToString(String.format("%s:%s",facadeConfig.getUser(),facadeConfig.getToken()).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("编码token，失败");
    }

    @AllArgsConstructor
    public static class InnerFacadeUrl {
        private FacadeConfig facadeConfig;
        private Request.Builder reqBuilder(){
            return new  Request.Builder();
        }
        protected String registerShop(){
            return String.format("%s/open/gateway/shopee/register",facadeConfig.getDomain());
        }
        public Request.Builder goodsList(){
            return reqBuilder();
        }
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println(Base64.getEncoder().encodeToString(("oms:84f6ef76844c43ca958a24902f5c3980").getBytes("UTF-8")));
    }
}
